<template>
  <div class="margin-container-list">
    <div class="bg-color-white">

      <!--出入库单状态切换 tab -->
      <div class="tab-style-default">
        <el-tabs v-model="tabActiveStatus" @tab-click="doChangeTab">
          <el-tab-pane :label="labels[0]" name="0"> </el-tab-pane>
          <el-tab-pane :label="labels[1]" name="1"> </el-tab-pane>
          <el-tab-pane :label="labels[2]" name="2"> </el-tab-pane>
          <el-tab-pane :label="labels[3]" name="3"> </el-tab-pane>
          <el-tab-pane v-if="warehouseObj.warehouseType == '2'" :label="labels[10]" name="10"> </el-tab-pane>
          <el-tab-pane :label="labels['all']" name="all"> </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 顶部搜索 -->
      <div class="mar-b-10">
        <div class="inline-flex">
          <el-select v-model="textCol" class="width-150">
            <el-option label="出入库单号" value="stockNo"></el-option>
            <el-option label="商品名称" value="goodsTitle"></el-option>
            <el-option label="商品货号" value="goodsCode"></el-option>
            <el-option label="SKU条码" value="goodsBarCode"></el-option>
            <el-option label="来源单号 " value="stockSourceNo"></el-option>
          </el-select>
          <el-input @keyup.enter.native="doSearch" v-model.trim="textValue" placeholder="请输入内容" class="width-200">
          </el-input>
        </div>
        <!-- 业务属性 -->
        <el-select placeholder="业务属性" v-model="defaultQuery.businessType" class="pad-l-10" clearable
          style="width: 120px;">
          <el-option label="所有入库" value="-1"></el-option>
          <el-option label="所有出库" value="-2"></el-option>
          <el-option v-for="(item, index) in dict.businessType" :key="index" :label="item" :value="index"></el-option>
        </el-select>
        <el-select placeholder="单据类型" v-model="defaultQuery.stockChangeType" class="pad-l-10" clearable
          style="width: 120px;">
          <el-option v-for="(item, index) in dict.stockChangeType" :key="index" :label="item" :value="index">
          </el-option>
        </el-select>
        <el-select v-if="warehouseObj.warehouseType == '2'" v-model="defaultQuery.failureReasons" placeholder="失败原因"
          class="pad-l-10" clearable style="width: 120px;">
          <el-option label="入库异常" value="入库异常"></el-option>
          <el-option label="入库关闭" value="入库关闭"></el-option>
          <el-option label="出库异常" value="出库异常"></el-option>
          <el-option label="出库关闭" value="出库关闭"></el-option>
        </el-select>
        <!-- 供应商 -->
        <el-select placeholder="供应商" v-model="defaultQuery.supplierId" class="pad-l-10" clearable>
          <el-option label="不限" value=" "></el-option>
          <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
            :value="item.supplierId"></el-option>
        </el-select>
        <div class="inline-flex">
          <!-- 时间筛选 -->
          <el-select v-model="dateTimeValue" class="pad-l-10" style="width: 120px;">
            <el-option label="创建时间" value="createTime"></el-option>
            <el-option label="提交时间" value="submitTime"></el-option>
            <el-option label="审核时间" value="auditTime"></el-option>
          </el-select>
          <el-date-picker v-model="dateTimePicker" type="datetimerange" range-separator="至"
            value-format="yyyy-MM-dd HH:mm:ss" :default-time="['00:00:00', '23:59:59']" start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </div>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="doSearch">查询</el-button>
          <el-button plain @click="doResetSearch">重置</el-button>
        </el-button-group>
      </div>
    </div>

    <div class="mar-b-10">
      <div
        v-if="warehouseObj.warehouseType === 1 || warehouseObj.warehouseType === 2 || warehouseObj.warehouseType === 3">
        <el-button v-if="tabActiveStatus == '0'" @click="doAdd" type="primary">添加</el-button>
        <el-button v-if="tabActiveStatus == '0'" @click="doBatchSubmit" type="primary">批量提交</el-button>
        <el-button v-if="tabActiveStatus == '0'" @click="doBatchDelete">批量删除</el-button>
        <el-button v-if="tabActiveStatus == '1' && warehouseObj.warehouseType == '1'" @click="doBatchAuditStock()"
          type="primary">批量审核</el-button>
        <el-button v-if="tabActiveStatus == '1'" @click="doBatchRevoke">批量撤销提交</el-button>
        <el-button @click="doExport">导出</el-button>
      </div>
      <div v-else-if="warehouseObj.warehouseType === 4">
        <el-button @click="doExport">导出</el-button>
      </div>
    </div>

    <!-- 内容列表 -->
    <div class="table-container">
      <el-table ref="multipleTable" :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
        element-loading-text="加载中">
        <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
        <el-table-column width="320px" label="出入库单" prop="stockNo"></el-table-column>
        <el-table-column width="180px" label="业务属性" prop="businessType">
          <template slot-scope="scope">
            {{ dict.businessType[scope.row.businessType] }}
          </template>
        </el-table-column>
        <el-table-column width="180px" label="单据类型" prop="stockChangeType">
          <template slot-scope="scope">
            {{ dict.stockChangeType[scope.row.stockChangeType] }}
          </template>
        </el-table-column>
        <el-table-column v-if="warehouseObj.warehouseType == '2'" width="180px" label="失败原因" prop="failureReasons">
          <template slot-scope="scope">
            {{ scope.row.failureReasons}}
            <br>
            {{scope.row.stockInOutFailedTime}}
          </template>
        </el-table-column>
        <el-table-column width="320px" label="来源单号" prop="stockSourceNo"></el-table-column>
        <el-table-column width="180px" label="商品总数量" prop="goodsTotalNum" align="center"></el-table-column>
        <el-table-column width="180px" label="供应商" prop="supplierName">
          <template slot-scope="scope">
            {{ scope.row.supplierName ? scope.row.supplierName : '不限' }}
          </template>
        </el-table-column>
        <el-table-column v-if="tabActiveStatus != '0' && tabActiveStatus != '1'" width="220px" label="审核意见"
          align="center">
          <template slot-scope="scope">
            <el-popover placement="top" width="200" trigger="click"
              :content="scope.row.auditRemark ? scope.row.auditRemark : '无'">
              <el-button type="text" slot="reference" v-if="scope.row.stockStatus !== 0 && scope.row.stockStatus !== 1">
                点击查看</el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column width="320px" label="操作" align="right" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="doLinkDetail(scope.row)">查看详情</el-button>
            <template
              v-if="warehouseObj.warehouseType === 1 || warehouseObj.warehouseType === 2 || warehouseObj.warehouseType === 3">
              <el-button v-if="scope.row.stockStatus == '0'" type="text" size="medium" @click="doEdit(scope.row)">编辑
              </el-button>
              <el-button v-if="scope.row.stockStatus == '0'" type="text" size="medium"
                @click="doSubmitStock(scope.row)">
                提交</el-button>
              <el-button v-if="scope.row.stockStatus == '1' && warehouseObj.warehouseType == '1'" type="text"
                size="medium" @click="doAuditStock(scope.row)">审核</el-button>
              <el-button v-if="scope.row.stockStatus == '1'" type="text" size="medium"
                @click="doRevokeStock(scope.row)">
                撤销提交</el-button>
              <el-button
                v-if="warehouseObj.warehouseType == 1 && (scope.row.businessType == '5' || scope.row.businessType == '10')"
                type="text" size="medium" @click="doCopyStock(scope.row)">复制</el-button>
              <el-button v-if="scope.row.stockStatus == '0'" type="text" size="medium"
                @click="doDeleteStock(scope.row)">
                删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 列表分页 -->
    <div class="pagination">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 入库单dialog -->
    <el-dialog :visible.sync="stockEditDialog" width="580px">
      <warehouse-stock-edit :showFlag="stockEditDialog" :stockOrder="stockFrom" @callback="doCallbackEditStock">
      </warehouse-stock-edit>
    </el-dialog>

    <!-- 审核dialog -->
    <el-dialog width="500px" title="出入库单审核" :visible.sync="auditVisible">
      <div v-loading="listLoading">
        <el-form ref="auditForm" :model="auditForm" label-width="120px" style="width: 460px">
          <el-form-item label="审核结果：" prop="stockStatus">
            <el-radio-group v-model="auditForm.stockStatus">
              <el-radio :label="2">审核通过</el-radio>
              <el-radio :label="3">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见：">
            <el-input type="textarea" :rows="3" v-model="auditForm.auditRemark"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer mar-b-10">
          <el-button type="primary" @click="doSaveAudit">确定</el-button>
          <el-button @click="auditVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    pagingStock,
    batchSubmit,
    batchDelete,
    deleteStock,
    doSubmit,
    copyStock,
    doRevoke,
    batchRevoke,
    doAudit,
    batchAudit,
    statStock,
    doExportByWarehouse
  } from '@/api/warehouse/warehouseStock'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    getWarehouse
  } from '@/api/warehouse/warehouseInfo'
  import elDragDialog from '@/directive/el-dragDialog'
  import warehouseStockEdit from '../components/warehouse-stock-edit'

  export default {
    components: {
      warehouseStockEdit
    },
    directives: {
      elDragDialog
    },
    data() {
      return {
        // tab model
        tabActiveStatus: '0',
        // 文本model
        textCol: 'stockNo',
        textValue: '',
        // 日期model
        dateTimeValue: 'createTime',
        dateTimePicker: [],
        // 查询条件
        searchListQuery: {},
        // 默认条件
        defaultQuery: {
          enterpriseId: '',
          warehouseId: '',
          currentPage: 1,
          size: 10,
          businessType: '',
          failureReasons: '',
          stockChangeType: '',
          supplierId: ''
        },
        // 数据字典
        dict: {
          businessType: {},
          stockChangeType: {}
        },
        // tab标签
        labels: {
          '0': '待提交(0)',
          '1': '待审核(0)',
          '2': '已完成(0)',
          '3': '审核未通过(0)',
          '10': '出入库失败(0)',
          'all': '全部出入库单(0)'
        },
        // tab标签模板
        labelTemp: {
          '0': '待提交(s)',
          '1': '待审核(s)',
          '2': '已完成(s)',
          '3': '审核未通过(s)',
          '10': '出入库失败(s)',
          'all': '全部出入库单(s)'
        },
        // 单据表单
        stockFrom: {
          stockId: '',
          businessType: '',
          supplierId: '',
          remark: ''
        },
        // 审核表单
        auditForm: {
          stockId: '',
          stockIds: [],
          stockStatus: 2,
          auditRemark: ''
        },
        // 仓库对象
        warehouseObj: {
          warehouseType: ''
        },
        supplierList: [],
        // 出入库单dialog
        stockEditDialog: false,
        // 审核弹窗
        auditVisible: false,
        listLoading: false,
        total: 0,
        dataList: [],
        multipleSelection: []
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.supplierId) {
        this.supplierId = queryParams.supplierId
      }
      if (queryParams && queryParams.currentPage) {
        this.searchListQuery.currentPage = queryParams.currentPage * 1
      }
      if (queryParams && queryParams.purchaseOrderNo) {
        this.textCol = 'stockSourceNo'
        this.textValue = queryParams.purchaseOrderNo
        this.tabActiveStatus = queryParams.tabActiveStatusName
      }
      // 获取仓库信息
      getWarehouse(this.getWarehouseId()).then((response) => {
        if (response.isError) return
        Object.assign(this.warehouseObj, response.data)
      })
      // 获取供应商列表
      listSupplier({
        enterpriseId: this.getEnterpriseId()
      }).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      this.stat()
      this.initList()
    },
    methods: {
      // tab切换事件
      doChangeTab() {
        this.doSearch()
      },
      // 设置查询条件
      setSearchListQuery() {
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery.enterpriseId = this.getEnterpriseId()
        this.searchListQuery.warehouseId = this.getWarehouseId()
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.dateColumn = this.dateTimeValue
        this.searchListQuery.startDate = (this.dateTimePicker && this.dateTimePicker.length > 0) ? this.dateTimePicker[
          0] : ''
        this.searchListQuery.endDate = (this.dateTimePicker && this.dateTimePicker.length > 1) ? this.dateTimePicker[
          1] : ''
        this.searchListQuery.stockStatus = this.tabActiveStatus
      },
      // 出入库表单列表
      initList() {
        this.listLoading = true
        this.setSearchListQuery()
        pagingStock(this.searchListQuery).then(response => {
          this.listLoading = false
          this.total = response.data.total
          this.dataList = response.data.records
          this.dict = response.data.dict
        })
      },
      // 统计出入库单各状态记录数
      stat() {
        statStock(this.getWarehouseId()).then(response => {
          if (response.isError) return
          this.labels[0] = this.labelTemp[0].replace('s', response.data[0])
          this.labels[1] = this.labelTemp[1].replace('s', response.data[1])
          this.labels[2] = this.labelTemp[2].replace('s', response.data[2])
          this.labels[3] = this.labelTemp[3].replace('s', response.data[3])
          this.labels[10] = this.labelTemp[10].replace('s', response.data[10])
          this.labels['all'] = this.labelTemp['all'].replace('s', response.data['all'])
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.dateTimeValue = originData.dateTimeValue
        this.dateTimePicker = originData.dateTimePicker
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 添加事件
      doAdd() {
        this.stockEditDialog = true
      },
      // 编辑
      doEdit(row) {
        const originData = this.$options.data()
        this.stockFrom = originData.stockFrom
        Object.assign(this.stockFrom, row)
        this.stockEditDialog = true
      },
      // 关闭出入库dialog事件
      doCallbackEditStock(callbackFlag) {
        if (callbackFlag) {
          this.initList()
        }
        this.stockEditDialog = false
      },
      // 单个提交
      doSubmitStock(row) {
        this.listLoading = true
        doSubmit(row.stockId).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '提交成功'
          })
          this.stat()
          this.initList()
        })
      },
      // 批量提交
      doBatchSubmit() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择出入库单'
          })
          return
        }
        this.listLoading = true
        const stockIds = selections.map(item => item.stockId)
        batchSubmit({
          stockIds: stockIds
        }).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          const data = response.data
          const msg = '共提交' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
          this.$message({
            type: 'success',
            message: msg
          })
          this.stat()
          this.initList()
        })
      },
      // 撤销提交
      doRevokeStock(row) {
        this.listLoading = true
        doRevoke(row.stockId).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '批量撤销提交成功'
          })
          this.stat()
          this.initList()
        })
      },
      // 批量撤销提交
      doBatchRevoke() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择出入库单'
          })
          return
        }
        this.listLoading = true
        const stockIds = selections.map(item => item.stockId)
        batchRevoke({
          stockIds: stockIds
        }).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '批量撤销提交成功'
          })
          this.stat()
          this.initList()
        })
      },
      // 删除
      doDeleteStock(row) {
        this.$confirm('此操作将删除该出入库单，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          deleteStock(row.stockId).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.stat()
            this.initList()
          })
        })
      },
      // 批量删除
      doBatchDelete() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择出入库单'
          })
          return
        }
        this.$confirm('此操作将批量删除出入库单，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          const stockIds = selections.map(item => item.stockId)
          batchDelete({
            stockIds: stockIds
          }).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            const data = response.data
            const msg = '共提交' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
            this.$message({
              type: 'success',
              message: msg
            })
            this.stat()
            this.initList()
          })
        })
      },
      // 复制事件
      doCopyStock(row) {
        this.listLoading = true
        copyStock(row.stockId).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '复制成功'
          })
          this.stat()
          this.initList()
        })
      },
      // 审核事件
      doAuditStock(row) {
        const originData = this.$options.data()
        this.auditForm = originData.auditForm
        this.auditForm.stockId = row.stockId
        this.auditVisible = true
      },
      // 批量审核事件
      doBatchAuditStock() {
        const selections = this.multipleSelection
        if (selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择出入库单'
          })
          return
        }
        const stockIds = selections.map(item => item.stockId)
        const originData = this.$options.data()
        this.auditForm = originData.auditForm
        this.auditForm.stockIds = stockIds
        this.auditVisible = true
      },
      // 审核保存事件
      doSaveAudit() {
        if (this.auditForm.stockIds.length > 0) {
          this.listLoading = true
          batchAudit(this.auditForm).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            const data = response.data
            const msg = '共提交' + data.total + '笔，成功' + data.success + '笔，失败' + data.failure + '笔'
            this.$message({
              type: 'success',
              message: msg
            })
            this.stat()
            this.initList()
            this.auditVisible = false
          })
        } else {
          this.listLoading = true
          doAudit(this.auditForm).then(response => {
            if (response.isError) {
              this.listLoading = false
              return
            }
            this.$message({
              type: 'success',
              message: '审核成功'
            })
            this.stat()
            this.initList()
            this.auditVisible = false
          })
        }
      },
      // 详情事件
      doLinkDetail(row) {
        this.$router.push({
          path: '/stock/warehouse-stock-details/index',
          query: {
            stockId: row.stockId
          }
        })
      },
      // 导出事件
      doExport() {
        if (this.dataList.length === 0) {
          this.$message({
            type: 'error',
            message: '暂无可导出数据'
          })
          return
        }
        let form = {
          enterpriseId: this.getEnterpriseId(),
          warehouseId: this.getWarehouseId()
        }
        if (this.multipleSelection.length > 0) {
          const stockIds = this.multipleSelection.map(item => item.stockId)
          form.stockIdList = stockIds.join(',')
        } else {
          this.setSearchListQuery()
          form = this.searchListQuery
        }
        window.open(doExportByWarehouse(form), '_blank')
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>

</style>
